<template>
  <div class="log_manage">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item">
          <span class="search-label">操作系统:</span>
          <Select v-model="operatSystem" @on-change="selectOption" :clearable='true'>
            <Option v-for="item in optionList" :value="item.id" :key="item.id">{{ item.resName }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">操作人员:</span>
          <Input v-model="operatPerson" :maxlength="100" @on-keyup='filterSpace'
                 placeholder="请输入">
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">操作时间:</span>
          <!-- <DatePicker type="daterange" :editable='false' :options="options2" placement="bottom-end" @on-change='changeTime' v-model='dataValue'></DatePicker> -->
          <DatePicker type="date" placement="bottom-end" placeholder="请选择" :editable='false' v-model='dataVal' @on-change='changeDate' :clearable='false'></DatePicker>
          </Col>
        <Col class="search-item">
          <Button class="search-btn" type='primary' @click.native='search'>查询</Button>
          <Button class="search-btn" style='margin-left:20px' @click.native="reSet">重置</Button>
        </Col>
      </Row>
      <Row type="flex"
           justify="end"
           class="search-item-right">
        <Col class="search-item">
        <Button class="search-btn" @click='exportData' :disabled='this.data1.length>0 ? false: true' v-if="hasPermission('moms:log:export')">导出</Button>
        </Col>
      </Row>
      </Row>
    </div>
    <Table stripe :loading='loading' class="table-list" ref="selection" :columns="columns1" :data="data1" @on-selection-change='selectItem' :height="this.tableHeight"></Table>
    <Row type="flex" justify='space-between' style="padding:20px">
      <Col>
        <Button class="module-menu-margin" @click="handleSelectAll" v-if="hasPermission(['moms:log:delete'])">{{btnTitle}}</Button>
            <Dropdown placement="top" @on-click='batchAll' v-if="hasPermission(['moms:org:delete'])">
              <Button class="check_all">批量操作</Button>
              <DropdownMenu slot="list" style="text-align:center">
                <!-- <DropdownItem name='1' v-if="hasPermission('moms:org:updatestatus')">批量关闭</DropdownItem>
                <DropdownItem name='2' v-if="hasPermission('moms:org:updatestatus')">批量开启</DropdownItem> -->
                <DropdownItem name='3' v-if="hasPermission('moms:log:delete')">批量删除</DropdownItem>
              </DropdownMenu>
            </Dropdown>
      </Col>
      <Col><Page :total="total" :page-size='pageSize' :current ='pageIndex' show-total show-sizer @on-change='changePageIndex' @on-page-size-change='changePageSize' /></Col>
    </Row>
  </div>
</template>

<script>
import { demandResourceList, logList, delSelectLogList, exportLog } from '@/api/system/log'
import { blobToXls } from '@/libs/blobToXls'
export default {
  name: 'logManage',
  data () {
    return {
      tableHeight: 0,
      dataVal: '',
      btnTitle: '全选',
      dataValue: [],
      loading: true,
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      operatSystem: '',
      operatPerson: '',
      searchPerson: '',
      operatTime: '',
      optionList: [], // 操作系统列表
      allStatus: true, // 全选状态
      selectArrry: [],
      startTime: null,
      endTime: null,
      columns1: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '日志时间',
          key: 'createdAt'
        },
        {
          title: '操作系统',
          key: 'appName'
        },
        {
          title: '操作人员',
          key: 'creatorName'
        },
        {
          title: 'IP地址',
          key: 'ip'
        },
        {
          title: '操作内容',
          key: 'functionName',
          width: 300
        }
      ],
      data1: [],
      options2: {
        shortcuts: [
          {
            text: '最近7天',
            value () {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              return [start, end]
            }
          },
          {
            text: '最近30天',
            value () {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              return [start, end]
            }
          }
        ]
      }
    }
  },
  watch: {
    selectArrry (val) {
      if (val.length === this.data1.length) {
        this.btnTitle = '取消全选'
        this.allStatus = false
      } else {
        this.btnTitle = '全选'
        this.allStatus = true
      }
    }
  },
  methods: {
    exportData () {
      // let instance = axios.creat({
      //   responseType: 'blob'// 返回数据的格式，可选值为arraybuffer,blob,document,json,text,stream，默认值为json
      // })
      exportLog({
        merchantId: this.$store.state.user.merchantId,
        fileName: 'log',
        type: 'EXCEL',
        operator: this.searchPerson,
        appId: this.operatSystem,
        startTime: this.startTime,
        endTime: this.endTime
      }).then(res => {
        if (res.status === 200) {
          blobToXls(res.data, '导出日志列表')
        } else {
          this.$Message.error(`${res.message}`)
        }
      })
    },
    handleSelectAll () {
      // this.allStatus = !this.allStatus
      this.$refs.selection.selectAll(this.allStatus)
    },
    selectItem (val) {
      // if (val.length === this.data1.length) {
      //   this.btnTitle = '取消全选'
      //   this.allStatus = false
      // } else {
      //   this.btnTitle = '全选'
      //   this.allStatus = true
      // }
      this.selectArrry = val.map(item => {
        return { id: item.id, status: item.status }
      })
    },
    // 批量删除按钮
    batchAll (val) {
      if (this.selectArrry.length > 0) {
        let arr = []
        this.selectArrry.forEach(item => {
          arr.push(item.id)
        })
        let param = arr
        this.$Modal.confirm({
          title: val === '1' ? '确认批量关闭吗？' : val === '2' ? '确认批量开启吗？' : '确认批量删除吗？',
          onOk: () => {
            if (val === '3') {
              this.delAll(param)
            }
          },
          onCancel: () => {}
        })
      } else {
        this.$Message.error('请至少选择一项操作')
      }
    },
    // 批量删除接口
    delAll (data) {
      delSelectLogList(data).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('删除成功！')
          this.getLogList()
          this.selectArrry = []
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    filterSpace () {
      this.operatPerson = this.operatPerson.replace(/\s+/g, '')
    },
    reSet () {
      // this.dataValue = this.options2.shortcuts[0].value()
      // this.startTime = new Date(this.formatDate(this.dataValue[0]) + ' ' + '00:00:00').getTime()
      // this.endTime = new Date(this.formatDate(this.dataValue[1]) + ' ' + '23:59:59').getTime()
      this.dataVal = this.formatDate(new Date())
      this.startTime = new Date(this.dataVal + ' ' + '00:00:00').getTime()
      this.endTime = new Date(this.dataVal + ' ' + '23:59:59').getTime()
      this.operatSystem = ''
      this.operatPerson = ''
      this.searchPerson = ''
      this.pageIndex = 1
      this.pageSize = 10
      this.getLogList()
    },
    search () {
      this.searchPerson = this.operatPerson
      this.pageIndex = 1
      this.getLogList()
    },
    changeDate (time) {
      this.pageIndex = 1
      this.dataVal = time
      this.startTime = new Date(this.dataVal + ' ' + '00:00:00').getTime()
      this.endTime = new Date(this.dataVal + ' ' + '23:59:59').getTime()
      this.getLogList()
    },
    // changeTime (time) {
    //   this.pageIndex = 1
    //   this.dataValue = time
    //   this.startTime = new Date(this.dataValue[0] + ' ' + '00:00:00').getTime()
    //   this.endTime = new Date(this.dataValue[1] + ' ' + '23:59:59').getTime()
    //   this.getLogList()
    // },
    changePageIndex (index) {
      this.pageIndex = index
      this.getLogList()
    },
    changePageSize (size) {
      this.pageIndex = 1
      this.pageSize = size
      this.getLogList()
    },
    selectOption (val) {
      this.operatSystem = val
      this.searchPerson = this.operatPerson
      this.pageIndex = 1
      this.getLogList()
    },
    getOperatSystem () {
      demandResourceList({ merchantId: this.$store.state.user.merchantId, resType: 0 }).then(res => {
        if (res.data.status === 200) {
          this.optionList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getLogList () {
      this.loading = true
      this.tableHeight = 0
      logList({
        merchantId: this.$store.state.user.merchantId,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        appId: this.operatSystem,
        creatorName: this.searchPerson,
        start: this.startTime,
        end: this.endTime
      }).then(res => {
        this.loading = false
        if (res.data.status === 200) {
          this.selectArrry = []
          this.data1 = res.data.data.records
          this.total = res.data.data.total
          if (res.data.data.records && res.data.data.records.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    formatTen (num) {
      return num > 9 ? (num + '') : ('0' + num)
    },
    formatDate (date) {
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      return year + '-' + this.formatTen(month) + '-' + this.formatTen(day)
    }
  },
  mounted () {
    // this.dataValue = this.options2.shortcuts[0].value()
    // this.startTime = new Date(this.formatDate(this.dataValue[0]) + ' ' + '00:00:00').getTime()
    // this.endTime = new Date(this.formatDate(this.dataValue[1]) + ' ' + '23:59:59').getTime()
    this.dataVal = this.formatDate(new Date())
    this.startTime = new Date(this.dataVal + ' ' + '00:00:00').getTime()
    this.endTime = new Date(this.dataVal + ' ' + '23:59:59').getTime()
    this.getOperatSystem()
    this.getLogList()
  }
}
</script>
<style lang="less">
.log_manage {
  .search-box{
    padding-top: 0;
  }
  .search-item,.search-item-btn{
    padding-top: 24px;
  }
  .search-box .search-item-left{
    width: 90%
  }
  .search-box .search-item-right{
    width: 10%;
  }
}
</style>
